package com.meepo.sdk.component.webview

import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Resources
import android.net.Uri
import android.os.Build
import android.util.AttributeSet
import android.util.Log
import android.webkit.*
import com.meepo.sdk.utils.GsonUtils

class H5Container @SuppressLint("SetJavaScriptEnabled") constructor(context: Context, attrs: AttributeSet?, defStyle: Int) :
    WebView(context, attrs, defStyle) {

    @JvmOverloads
    constructor(context: Context, attrs: AttributeSet? = null) : this(
        context,
        attrs,
        Resources.getSystem().getIdentifier("webViewStyle", "attr", "android")
    )


    @SuppressLint("JavascriptInterface")
    override fun addJavascriptInterface(`object`: Any, name: String) {
        super.addJavascriptInterface(`object`, name)
    }

    fun addJavascriptInterface(`object`: Any) {
        this.addJavascriptInterface(`object`, DEFAULT_INTERFACE_NAME)
    }


    // must called in onPageStarted
    fun setVars(key: String, value: String) {
        this.loadUrl(with(String) { format("javascript:var %s = '%s'", key, value) })
    }

    // must called in onPageStarted
    fun setVars(key: String, value: Int) {
        this.loadUrl(with(String) { format("javascript:var %s = %d", key, value) })
    }

    fun setJSCode(code: String) {

        this.loadUrl(with(String) { format("javascript:%s", code) })
    }

    fun callJSFuncWithString(jsFuncName: String, stringParam: String) {

        val p = with(String) { format("String('%s')", stringParam) }

        val js = with(String) { format("javascript:%s(%s)", jsFuncName, p) }
        this.loadUrl(js)
    }

    fun callJSFuncWithJson(jsFuncName: String, jsonStringParam: String) {

//        var p = ""
//        if (!params.isNullOrEmpty()) {
//            p = params.joinToString { with(String) { format("\"%s\"", it) } }
//        }

//        var p = ""
//        if (!params.isNullOrEmpty()) {
//            p = params.joinToString { with(String) { format("\"%s\"", it) } }
//        }

        val p = with(String) { format("JSON.stringify(%s)", jsonStringParam) }

        this.loadUrl(with(String) { format("javascript:%s(%s)", jsFuncName, p) })
    }

    companion object {
        private const val DEFAULT_INTERFACE_NAME = "androidFunc"
    }

    init {
        val webSettings = this.settings

        // 设置与Js交互的权限
        webSettings.javaScriptEnabled = true
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE
        webSettings.allowContentAccess = true
        webSettings.allowFileAccess = true
        webSettings.domStorageEnabled = true
        webSettings.allowFileAccessFromFileURLs = true
        webSettings.allowUniversalAccessFromFileURLs = true
        webSettings.allowContentAccess = true
        webSettings.blockNetworkImage = false
        // https 加载 http资源
        webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW

        this.webChromeClient = object : WebChromeClient() {
            /**
             * // 设置允许JS弹窗
             * @param view
             * @param url
             * @param message
             * @param result
             * @return
             */
            override fun onJsAlert(view: WebView, url: String, message: String, result: JsResult): Boolean {
                return super.onJsAlert(view, url, message, result)
            }

            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                super.onProgressChanged(view, newProgress)

            }
        }
    }
}